package com.netmi.myuploadfileretrofit;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.sdk.android.vod.upload.VODSVideoUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClient;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.VODUploadCallback;
import com.alibaba.sdk.android.vod.upload.model.SvideoInfo;
import com.alibaba.sdk.android.vod.upload.session.VodHttpClientConfig;
import com.alibaba.sdk.android.vod.upload.session.VodSessionCreateInfo;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.PlayerControlView;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.hw.videoprocessor.VideoProcessor;
import com.hw.videoprocessor.util.VideoProgressListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class PlayVideoActivity extends AppCompatActivity {

    private Button  btPlayVideo;
    private TextView tvAddress;
    private ImageButton ivFullScreen;

    String videoPath = null;


    //设置EXOplayer播放参数
    //1.默认的播放View
    private PlayerView playerView;
//    private PlayerControlView playerControlView;//另一个播放界面
    //2.您可以ExoPlayer使用创建实例ExoPlayerFactory。工厂提供了一系列方法来创建ExoPlayer具有不同
    //级别自定义的实例。对于绝大多数用例，ExoPlayerFactory.newSimpleInstance应该使用其中一种 方法。
    //这些方法返回SimpleExoPlayer
    private SimpleExoPlayer player = null;
    // Produces DataSource instances through which media data is loaded.--生成加载媒体数据的数据源实例。
    private DataSource.Factory dataSourceFactory = null;
    // This is the MediaSource representing the media to be played.---这是表示要播放的媒体的媒体源
    private MediaSource videoSource = null;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);//（必须在setContentView 之前有效）
        setContentView(R.layout.activity_play_video);

        videoPath = getIntent().getStringExtra("videoPath");

        ivFullScreen = findViewById(R.id.full_screen);
        playerView = findViewById(R.id.player_view);
//        playerControlView= findViewById(R.id.player_control_view);
        btPlayVideo = findViewById(R.id.bt_start_play_video);
        tvAddress = findViewById(R.id.tv_video_address);
        tvAddress.setText("视频地址："+videoPath);

        creatVideoPlayer(PlayVideoActivity.this);
        prepareVideoSourse(videoPath);
        btPlayVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (player != null && !TextUtils.isEmpty(videoPath)) {
                    player.setPlayWhenReady(true);
                } else {
                    Toast.makeText(PlayVideoActivity.this, "选择视频后才能播放", Toast.LENGTH_SHORT).show();
                }
            }
        });


        ivFullScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= 21) {
                    View decorView = getWindow().getDecorView();
                    decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                    getWindow().setStatusBarColor(Color.TRANSPARENT);
                }
                //判断当前屏幕方向
                if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    //切换竖屏
                    PlayVideoActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    //切换横屏
                    PlayVideoActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            }
        });

    }









    private void addPlayerListener() {
        // 注册播放器监听
        player.addListener(new Player.EventListener() {
            @Override
            public void onTimelineChanged(Timeline timeline, @Nullable Object manifest, int reason) {
                String content = "当时间轴和/或清单被刷新时调用。\n" +
                        "注意，如果时间轴发生了变化，那么位置不连续也可能发生。例如，由于从时间轴中添加或删除了句点，当前句点索引可能已经更改。这将不会通过对onPositionDiscontinuity(int)的单独调用报告。\n" +
                        "参数:时间轴-最新的时间轴。永远不要为空，但可能是空的。\n" +
                        "舱单-最新的舱单。可能是null。\n" +
                        "原因-玩家。TimelineChangeReason负责此时间线更改。";
                Log.d("tgw", "onTimelineChanged: i=" + reason + "发生情况" + content);
            }

            @Override
            public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
                String content = "默认的void onTracksChanged(TrackGroupArray trackGroups，\n" +
                        "TrackSelectionArray trackSelections)\n" +
                        "当可用轨道或选定轨道发生更改时调用。\n" +
                        "参数:trackGroups—可用的曲目。决不为空，但长度可能为零。\n" +
                        "trackselection——每个渲染器的轨迹选择。决不为空，且长度始终为Player.getRendererCount()，但可能包含空元素。";
                Log.d("tgw", "onTracksChanged: " + content);
            }

            @Override
            public void onLoadingChanged(boolean isLoading) {

                String content = "当播放器开始或停止加载源文件时调用。\n" +
                        "参数:isLoading—当前是否正在加载源文件。";
                Log.d("tgw", "onLoadingChanged: isLoading" + isLoading + "---" + content);
            }

            @Override
            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                //Player.STATE_IDLE：这是初始状态，播放器停止时的状态以及播放失败时的状态。
                //Player.STATE_BUFFERING：玩家无法立即从当前位置进行游戏。这主要是因为需要加载更多数据。
                // Player.STATE_READY：玩家可以立即从当前位置进行游戏。
                //Player.STATE_ENDED：播放器播放完所有媒体。
                String content = "当从Player.getPlayWhenReady()或Player.getPlaybackState()返回的值发生更改时调用。\n" +
                        "参数:播放时准备-是否播放将继续时准备。\n" +
                        "状态常量之一。";
                Log.d("tgw", "onPlayerStateChanged: playWhenReady" + playWhenReady + "---playbackState:" + playbackState + "---" + content);
            }

            @Override
            public void onRepeatModeChanged(int repeatMode) {
                String content = "当Player.getRepeatMode()的值发生更改时调用。\n" +
                        "参数:重复模式-播放器。用于回放的重复模式。";
                Log.d("tgw", "onRepeatModeChanged: repeatMode" + repeatMode + "---" + content);

            }

            @Override
            public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
                String content = "当Player.getShuffleModeEnabled()的值发生更改时调用。\n" +
                        "参数:shuffleModeEnabled -是否启用窗口的改组。";
                Log.d("tgw", "onShuffleModeEnabledChanged: shuffleModeEnabled" + shuffleModeEnabled + "---" + content);

            }

            @Override
            public void onPlayerError(ExoPlaybackException error) {
                String content = "默认空onPlayerError(外部playbackexception错误)\n" +
                        "发生错误时调用。播放状态将转换到播放器。调用此方法后立即执行STATE_IDLE。player实例仍然可以使用，如果不再需要player .release()，则仍然必须调用它。\n" +
                        "参数:错误-错误。";
                Log.d("tgw", "onPlayerError: error" + error + "---" + content);

            }

            @Override
            public void onPositionDiscontinuity(int reason) {
                String content = "当位置不连续而不更改时间轴时调用。一段位置不连续发生在当前窗口或指数变化(由于回放过渡时间表从一个时期到下一个),或者当回放位置跳跃在正在播放(作为寻求执行的结果,或当源引入了内部不连续)。\n" +
                        "位置不连续是由于位置的变化而发生的";
                Log.d("tgw", "onPositionDiscontinuity: reason" + reason + "---" + content);

            }

            @Override
            public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
                String content = "当当前回放参数更改时调用。回放参数可能会由于调用player . setplaybackparameters (PlaybackParameters)而更改，或者播放器本身也可能更改这些参数(例如，如果音频回放切换到直通模式，则不再可能进行速度调整)。\n" +
                        "参数:播放参数-播放参数。";
                Log.d("tgw", "onPlaybackParametersChanged: playbackParameters" + playbackParameters + "---" + content);

            }

            @Override
            public void onSeekProcessed() {
                String content = "当玩家处理完所有挂起的请求后调用。在向onPlayerStateChanged(boolean, int)报告了对播放器状态的任何必要更改之后，保证会发生这种情况。";
                Log.d("tgw", "onSeekProcessed: " + "---" + content);

            }
        });

    }











    private void creatVideoPlayer(Activity context) {
        player = new SimpleExoPlayer.Builder(context).build();
        // Bind the player to the view.
        playerView.setPlayer(player);
//        playerControlView.setPlayer(player);
        // Produces DataSource instances through which media data is loaded.
        dataSourceFactory = new DefaultDataSourceFactory(context,
                Util.getUserAgent(context, "myuploadfileretrofit"));
    }

    private void prepareVideoSourse(String videoAddress) {
        Uri mp4VideoUri = Uri.parse(videoAddress);
        player.setRepeatMode(Player.REPEAT_MODE_ONE);//无限循环
        // This is the MediaSource representing the media to be played.
        videoSource =
                new ProgressiveMediaSource.Factory(dataSourceFactory)
                        .createMediaSource(mp4VideoUri);
        // Prepare the player with the source.
        player.prepare(videoSource);
        player.setPlayWhenReady(false);//控制播放暂停开始

    }


    @Override
    public void onBackPressed() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            //切换竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }else {
            super.onBackPressed();
        }
    }

}
